package com.chinacoal.microservice.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhuliang
 * @version V1.0
 * @Description: 生成订单号和token的工具类
 * @date 2020-12-25 14：27
 */
public class OrderNumberUtil {
    //密钥
    private static final String TOKEN_SECRET = "5R5roUcuAu3o5C3oZhu";

    /** 支付订单类别 */
    private static final Integer PAY_CODE = 1;
    /** 开票订单类别 */
    private static final Integer INVOICE_ORDER_CODE = 2;

    /**
     * 根据uuid生成支付订单的订单号
     */
    public static String toPayCode(String id) {
        //开头14位时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dayTime = sdf.format(new Date());

        //生成uuid的hashCode值
        int hashCode = id.hashCode();

        //可能为负数
        if(hashCode < 0){
            hashCode = -hashCode;
        }

        //生成2位随机数
        int random = new Random().nextInt(99);

        //算法实现：14位时间 + uuid的hashCode的16位订单号 + 1位类别 + 2位随机数
        String value = dayTime + String.format("%015d", hashCode) + PAY_CODE + String.format("%02d",random);

        return value;
    }

    /**
     * 根据uuid生成支付订单的订单号
     */
    public static String toInvoiceCode(String id) {
        //开头14位时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dayTime = sdf.format(new Date());

        //生成uuid的hashCode值
        int hashCode = id.hashCode();

        //可能为负数
        if(hashCode < 0){
            hashCode = -hashCode;
        }

        //生成2位随机数
        int random = new Random().nextInt(99);

        //算法实现：14位时间 + uuid的hashCode的16位订单号 + 1位类别 + 2位随机数
        String value = dayTime + String.format("%015d", hashCode) + INVOICE_ORDER_CODE + String.format("%02d",random);

        return value;
    }

    //加密
    public static String sign(String phone) {
        try {
            long timeMillis = System.currentTimeMillis();
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            Map<String, Object> headerMap = new HashMap<>(2);
            headerMap.put("type", "JWT");
            headerMap.put("alg", "HS256");
            return JWT.create().withHeader(headerMap).withClaim("phone", phone).withClaim("time",timeMillis).sign(algorithm);
        } catch (Exception e) {
            return null;
        }
    }

    //解密
    public static DecodedJWT verifyJwt(String token) throws Exception{
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        JWTVerifier jwtVerifier = JWT.require(algorithm).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        return decodedJWT;
    }
}
